package com.gf.exam.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gf.base.dao.impl.BaseDaoImpl;
import com.gf.common.bean.Page;
import com.gf.exam.dao.AnswerDao;
import com.gf.exam.mapper.AnswerMapper;
import com.gf.exam.model.Answer;

@Service("answerDao")
public class AnswerDaoImpl extends BaseDaoImpl implements AnswerDao {

	/**
	 * insert into answer (userId,username,examId,cellNo,createtime) values
	 * (?,?,?,?,current_timestamp)
	 */
	@Value("${answerDao.insertSql}")
	private String insertSql;

	/**
	 * select * from answer where id=?
	 */
	@Value("${answerDao.queryByIdSql}")
	private String queryByIdSql;

	@Value("${answerDao.querytotalSql}")
	private String querytotalSql;

	/**
	 * select * from answer where examId=? order by createtime desc
	 */
	@Value("${answerDao.queryByExamIdSql}")
	private String queryByExamIdSql;

	/**
	 * select examId from answer where userId=? order by createtime desc
	 */
	@Value("${answerDao.queryParticipateSql}")
	private String queryParticipateSql;

	@Override
	public long insert(long userId, String username, long examId, int cellNo) {

		return this.insertWithIdReturn(insertSql, userId, username, examId,
				cellNo);
	}

	@Override
	public Answer queryById(long id) {

		List<Answer> answers = jdbcTemplate.query(queryByIdSql,
				new Object[] { id }, AnswerMapper.getMapper());
		if (answers != null && answers.size() > 0) {
			return answers.get(0);
		}
		return null;
	}

	@Override
	public List<Answer> queryByExamId(long examId) {
		return jdbcTemplate.query(queryByExamIdSql, new Object[] { examId },
				AnswerMapper.getMapper());
	}

	@Override
	public List<Answer> queryByExamId(long examId, int currentPage, int pageSize) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);

		return getPaginationResult(queryByExamIdSql, page,
				AnswerMapper.getMapper(), examId);
	}

	@Override
	public int queryNumberByExamId(long examId) {
		List<Answer> result = queryByExamId(examId);
		if (result == null) {
			return 0;
		}
		return result.size();
	}

	@Override
	public List<Long> queryParticipate(long userId) {
		return jdbcTemplate.queryForList(queryParticipateSql, Long.class,
				userId);
	}

	@Override
	public int queryAllCount() {
		return jdbcTemplate.queryForInt(querytotalSql);
	}

}
